<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
      </el-row>

      <!-- table列表数据区域 -->
      <el-table :data="RolesList" height="420px" border style="width: 100%">
        <el-table-column align="center" type="expand" width="50" label="展开">
          <template v-slot="scoped">
            <el-row
              :class="['bdbottom',i1 == 0?'bdtop' :'','vcenter']"
              v-for="(item1,i1) in scoped.row.children"
              :key="item1.id"
            >
              <!-- 渲染第一级权限 -->
              <el-col :span="5">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[(item1.children.length>1 && i2 !== item1.children.length - 1)? 'bdbottom' : '','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scoped.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scoped.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色名称" width="180"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="operation">
            <!-- 修改用户信息 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRolesInfo(operation.row)"
            >编辑</el-button>
            <!-- 删除用户 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(operation.row)"
            >删除</el-button>
            <!-- 分配权限 -->
            <el-button
              size="mini"
              type="info"
              icon="el-icon-setting"
              @click="showRightsDialog(operation.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialogVisible"
      width="40%"
      @close="addNewRolesCloes"
    >
      <el-form
        :model="RolesFormData"
        :rules="RolesFormRules"
        ref="RolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input type="text" v-model="RolesFormData.roleName" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input type="text" v-model="RolesFormData.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色的对话框 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="eaitRolesDialogVisible"
      width="40%"
      @close="addNewRolesCloes"
    >
      <el-form
        :model="RolesFormData"
        :rules="RolesFormRules"
        ref="editRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input type="text" v-model="RolesFormData.roleName" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input type="text" v-model="RolesFormData.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eaitRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfoSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框default-expand-all -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible_Rights"
      width="30%"
      @close="dialogRightsClose"
    >
      <el-tree
        :data="RolesTree"
        show-checkbox
        node-key="id"
        ref="treeRef"
        :expand-on-click-node="true"
        highlight-current
        :props="defaultProps"
        :default-checked-keys="defKeys"
        :render-after-expand="true"
        :default-expanded-keys="defaultKey"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_Rights = false">取 消</el-button>
        <el-button type="primary" @click="editRolesRights_Tree">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      RolesFormData: {
        roleName: "",
        roleDesc: ""
      },
      RolesFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 8,
            message: "角色名称需在2-8个字符间",
            trigger: "blur"
          }
        ]
      },
      RolesList: [],
      addRolesDialogVisible: false, //控制添加角色对话框显示和隐藏
      eaitRolesDialogVisible: false, //修改控制弹出框
      dialogVisible_Rights: false, //控制权限设置对话框显示和隐藏
      RolesTree: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      //默认选中的节点id
      defKeys: [],
      rolesId: "",
      activData: "",
      defaultKey: [101, 104] // 默认展开的节点
    };
  },
  created: function() {
    this.getRolesList();
  },
  methods: {
    addNewRoles: function() {
      // 先检查表单是否通过验证
      this.$refs.RolesFormRef.validate(async valid => {
        if (!valid) {
          this.$message.warning("请检查输入的信息是否有误!");
          return;
        }
        const { data: res } = await this.$http.post(
          "/roles",
          this.RolesFormData
        );
        if (res.meta.status != 201) {
          this.$message.error("创建角色失败!");
          console.log(res.meta);
          return;
        }
        this.$message.success("创建角色成功!");
        this.addRolesDialogVisible = false;
        this.getRolesList(); //更新列表
      });
    },
    addNewRolesCloes: function() {
      this.RolesFormData.roleName = "";
      this.RolesFormData.roleDesc = "";
      this.rolesId = ""; //清空当前编辑的角色id
    },
    editRolesInfo: async function(_UserInfo) {
      //点击修改按钮的函数
      // 打开对话框
      this.eaitRolesDialogVisible = true;
      this.rolesId = _UserInfo.id; //把当前编辑的角色id存起来
      //先从服务端获取最新的数据(避免数据有延迟)
      const { data: res } = await this.$http.get("/roles/" + this.rolesId);
      if (res.meta.status !== 200) {
        this.$message.error("获取后台数据失败");
        return;
      }
      this.RolesFormData.roleName = res.data.roleName;
      this.RolesFormData.roleDesc = res.data.roleDesc;
    },
    editRolesInfoSubmit: function() {
      //修改提交按钮
      // 先检查表单是否通过验证
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) {
          this.$message.warning("请检查输入的信息是否有误,否则无法提交!");
          return;
        }
        const { data: res } = await this.$http.put(
          "/roles/" + this.rolesId,
          this.RolesFormData
        );
        if (res.meta.status != 200) {
          this.$message.error("修改角色失败!");
          console.log(res.meta);
          return;
        }
        this.$message.success("修改角色成功!");
        this.eaitRolesDialogVisible = false;
        this.getRolesList(); //更新列表
      });
    },
    deleteRoles: function(_UserInfo) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            "/roles/" + _UserInfo.id
          );
          if (res.meta.status != 200) {
            this.$message({
              message: "删除失败",
              type: "warning"
            });
            return;
          }
          this.$message.success("删除成功!");
          this.getRolesList();
        })
        .catch(() => {
          //取消不做操作
        });
    },
    getRolesList: async function() {
      const { data: res } = await this.$http.get("/roles");
      if (res.meta.status != 200) {
        this.$message({
          message: "获取角色列表数据失败",
          type: "warning"
        });
        return;
      }

      const that = this;
      res.data.forEach(item_first => {
        // 对获取过来的数组数据排好序,以便呈现到页面
        item_first.children.forEach(item_two => {
          item_two.children.sort(that.compare("id", true));
        });
      });
      this.RolesList = res.data;
    },
    removeRightById: function(_role, _rightId) {
      // 根据id删除对应的权限

      const that = this;
      this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        lockScroll: false
      })
        .then(async () => {
          const { data: res } = await that.$http.delete(
            `/roles/${_role.id}/rights/${_rightId}`
          );
          if (res.meta.status !== 200) {
            that.$message.error("删除权限失败");
            return;
          }
          that.$message.success("删除权限成功");
          //   this.getRolesList();不能使用这个,否则会导致列表被重新刷新,效果不好
          _role.children = res.data;
        })
        .catch(err => err);
    },
    showRightsDialog: async function(_UserInfo) {
      //分配权限按钮
      // 获取所有权限的数据
      this.dialogVisible_Rights = true;

      this.rolesId = _UserInfo.id; //把当前编辑的角色id存起来,
      this.activData = _UserInfo; //当前编辑的这条的用户信息存起来
      const that = this;
      // defKeys数组存起来获取所拥有的权限(用来选中)
      //每次先清空保存id用来选中的数组
      that.defKeys = [];
      const { data: res } = await this.$http.get("/rights/tree ");
      if (res.meta.status != 200) {
        this.$message.error("获取权限数据失败!");
        return;
      }
      this.RolesTree = res.data;
      this.getRightId(_UserInfo, this.defKeys);
    },
    getRightId: function(node, arr) {
      //方法函数,获取用户拥有的最后一层权限,得到让树形选中的id
      // 利用递归算法遍历
      if (!node.children) {
        //如果没有children节点了,就return出去中断递归
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        // 如果还有children继续遍历
        this.getRightId(item, arr);
      });
    },
    compare: function(property, desc) {
      //排序数组
      return function(a, b) {
        var value1 = a[property];
        var value2 = b[property];
        if (desc == true) {
          // 升序排列
          return value1 - value2;
        } else {
          // 降序排列
          return value2 - value1;
        }
      };
    },
    editRolesRights_Tree: async function() {
      //点击权限设置对话框的确定函数
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = key.join(",");
      const { data: res } = await this.$http.post(
        "/roles/" + this.rolesId + "/rights",
        {
          rids: idStr
        }
      );
      if (res.meta.status != 200) {
        this.$message.error("权限设置未成功");
        return;
      }
      this.$message.success("权限设置成功");

      // 为了避免直接刷掉列表,从重新获取最新的数据,修改把对应插槽中的数据operation.row指向activData(为了能更新数据时候列表不刷新而是刷新视图效果)    rearrangement(res.data);
      // 发送请求得到最新的数据needUpdateData
      const { data: res2 } = await this.$http.get("/roles/");

      //循环根据id找到对应的角色
      const needUpdateData = res2.data.filter(item => {
        return item.id == this.rolesId;
      });

      // 把最新的数据needUpdateData放到插槽数据里面(this.activData存的就是插槽数据,指针也指向插槽数据),
      var newData = needUpdateData[0].children;
      const that = this;
      newData.forEach(item_first => {
        // 对获取过来的数组数据排好序,以便呈现到页面
        item_first.children.sort(that.compare("id", true));
      });
      this.activData.children = newData;

      this.dialogVisible_Rights = false;
    },
    dialogRightsClose: function() {
      this.defKeys = []; //关闭时清空保存id用来选中的数组
      this.rolesId = ""; //清空当前编辑的角色id
    }
  }
};
</script>
<style lang='less' scoped>
.box-card {
  height: calc(100vh - 150px);
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>